package com.pig.live.common.utils.app;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 从应用的Spring环境中获取Bean对象和获取上下文的工具类
 * 实现ApplicationContextAware接口，就能获取当前所处的Spring 上下文
 *
 * @author gaojx
 * @since 2020/8/9
 */
@Component
public class AppContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    /**
     * 将当前应用中所有Bean所处的Spring环境（入参）设置给AppContextUtils中的applicationContext
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        AppContextUtils.applicationContext = applicationContext;
    }

    /**
     * 获取当前应用的上下文
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据名称获取Bean
     * @param beanName
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName){
        return (T) applicationContext.getBean(beanName);
    }

    /**
     * 根据类型获取Bean
     * @param c
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> c){
        return (T) applicationContext.getBean(c);
    }
}
